﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.ServiceProcess;
using Sustainalytics.ClientDW.Tracing;
using Microsoft.Owin.Hosting;

namespace Sustainalytics.Synchronization.Service
{
    public partial class WindowsService : ServiceBase
    {
        public static string Name = "Sustainalytics Synchronization Service";
        
        public WindowsService()
        {
            InitializeComponent();

            ServiceName = Name;
        }

        protected override void OnStart(string[] args)
        {
            StartServices();
        }

        protected override void OnStop()
        {
        }

        public void StartServices()
        {
            try
            {
                var hostUrl = ConfigurationManager.AppSettings["HostUrl"];

                EventLog.WriteEntry(ServiceName, "Sustainalytics Client synchronization starting on " + hostUrl + "...", EventLogEntryType.Information);
                ClientDWEventSource.Log.Message(string.Format("Sustainalytics Client synchronization starting on " + hostUrl + "..."));

                WebApp.Start<Startup>(hostUrl);

                EventLog.WriteEntry(ServiceName, "Sustainalytics Client synchronization running on " + hostUrl, EventLogEntryType.Information);
                ClientDWEventSource.Log.Message(string.Format("Sustainalytics Client synchronization running on " + hostUrl));
                Console.WriteLine("{0} running on {1}", ServiceName, hostUrl);
            }
            catch (Exception e)
            {
                ClientDWEventSource.Log.Error(string.Format("OnStart error: {0} Inner Exception: {1}", e.Message, e.InnerException != null ? e.InnerException.Message : string.Empty));
                
                EventLog.WriteEntry(ServiceName,
                    string.Format("OnStart error: {0} Inner Exception: {1}", e.Message, e.InnerException != null ? e.InnerException.Message : string.Empty),
                    EventLogEntryType.Error);
                
                Console.WriteLine(e);
            }
        }
    }
}
